package res;


import com.codahale.metrics.annotation.Timed;
import io.dropwizard.jersey.PATCH;
import mybatis.UserDao;
import mybatis.conf.MybatisConf;
import org.apache.ibatis.session.SqlSession;
import org.hibernate.validator.constraints.NotEmpty;
import orm.*;
import util.JWTToken;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;


/**
 * Created by langdon on 2017/7/21.
 */

@Path("/api/v1/users")
@Produces(MediaType.APPLICATION_JSON)
public class UserRes {

    public UserRes() {
        System.out.println("UserRes");
    }


    /************************************用户登录后需要认证的操作****************************************/
    @GET
    @Path("/{auth}")
    @Timed
    public  Result getUser(
            @PathParam("auth") String auth
    ){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {
            UserDao userDao = sqlSession.getMapper(UserDao.class);

            int userId = Integer.parseInt((String)JWTToken.decode(auth).getPayload().get("id"));
            User user = userDao.getByUId(userId);
            sqlSession.close();
            if(user!=null)
                return new UserResult(Status.SUCCESS,"Success" ,user);
            else return new Result(Status.NOT_FOUND,"Can not find this user :"+user);
        }
        finally {
            sqlSession.close();
        }
    }


    @POST
    @Timed
    public  Result registerUser(@NotEmpty @QueryParam("user") String username,
                               @NotEmpty @QueryParam("password") String password,
                               @NotEmpty @QueryParam("phoneNumber") String phoneNumber,
                               @NotEmpty @QueryParam("mailbox") String mailbox,
                               @QueryParam("introduction")String introduction){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {
            UserDao userDao = sqlSession.getMapper(UserDao.class);

            User theUser = userDao.getByName(username);
            if(theUser != null){
                return new Result(Status.DUPLICATE,"This username has been used!");
            }
            theUser = new User();
            theUser.setUserName(username);
            theUser.setPhoneNumber(phoneNumber);
            theUser.setPassword(password);
            theUser.setMailbox(mailbox);
            theUser.setIntroduction(String.valueOf(this.hashCode()));
            userDao.add(theUser);
            sqlSession.commit();
            sqlSession.close();
            return new UserResult(Status.SUCCESS,"Register Success!",theUser);
        }
        finally
        {
            sqlSession.close();
        }
    }

    @PUT
    @Timed
    public  Result resetPassword(@NotEmpty @QueryParam("user") String user,
                                @NotEmpty @QueryParam("oldPwd") String oldPwd,
                                @NotEmpty @QueryParam("newPwd") String newPwd){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {

            UserDao userDao = sqlSession.getMapper(UserDao.class);

            User theUser = userDao.getByName(user);

            if(theUser == null){
                return new Result(Status.NOT_FOUND,"Can not find this username!");
            }
            if(theUser.getPassword().equals(oldPwd)){
                theUser.setPassword(newPwd);
                userDao.update(theUser);
                sqlSession.commit();
                return new UserResult(Status.SUCCESS,"Success！",theUser);
            }else{
                return new Result(Status.ERROR , "Please enter the right old password!");
            }
        }
        finally
        {
            sqlSession.close();
        }
    }

    @PATCH
    @Timed
    public   Result updateUser(
            @NotEmpty @QueryParam("auth") String auth,
            @QueryParam("phoneNumber") String  phoneNumber,
            @QueryParam("mailbox") String mailbox,
            @QueryParam("introduction")String introduction
    ){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            int userId = Integer.parseInt((String)JWTToken.decode(auth).getPayload().get("id"));
            User theUser = userDao.getByUId(userId);

            if(theUser==null){
                new Result(Status.NOT_FOUND,"Can not find such user!");
            }

            if(phoneNumber!=null)
                theUser.setPhoneNumber(phoneNumber);

            if(mailbox != null)
                theUser.setMailbox(mailbox);

            if(introduction !=null)
                theUser.setIntroduction(introduction);

            userDao.update(theUser);
            sqlSession.commit();

            theUser=userDao.getByUId(userId);
            return new UserResult(Status.SUCCESS,"Success!",theUser);
        }
        finally {
            sqlSession.close();
        }

    }

    /**************************************无需认证的资源请求************************************/

    @GET
    @Path("/name/{username}")
    @Timed
    public Result getByName(@PathParam("username") String username){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            User theUser = userDao.getByName(username);
            if(theUser == null){
                return new Result(Status.NOT_FOUND,"Can not find such user!");
            }else{
                theUser.setPassword("******");//掩盖密码
                return new UserResult(Status.SUCCESS,"Success!",theUser);
            }
        }
        finally {
            sqlSession.close();
        }
    }

    @GET
    @Path("/userId/{id}")
    @Timed
    public Result getById(@PathParam("id")int id){
        SqlSession sqlSession = MybatisConf.getSession();
        try
        {
            UserDao userDao = sqlSession.getMapper(UserDao.class);
            User user = userDao.getByUId(id);
            if(user==null){
                return new Result(Status.NOT_FOUND,"Can not find such user!");
            }else{
                user.setPassword("*****");
                return new UserResult(Status.SUCCESS,"Success!",user);
            }
        }
        finally {
            sqlSession.close();
        }

    }


}
